<template>
  <a-modal v-model:visible="showAdjustTime" title-align="start" width="600px"  >
    <template #title>
      <div class="header">
        <custom-title title="调整任务计划" />
      </div>
    </template>
    <div class="customer-info">{{ formData.customerName }}丨{{ formData.residence }} 丨{{ formData.taskName }}</div>
    <a-form class="plan-form" ref="formRef" :model="formData" :rules="formRule" label-width="150px" a-loading="isLoading">
      <a-form-item label="计划时间范围" field="timeRange">
        <a-range-picker
          :disabledDate="(date) => date < new Date()- 8.64e7"
          v-model="formData.timeRange"
          range-separator="至"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="changeDate"
        />
      </a-form-item>
      <a-form-item label="计划工期" field="executeDays">
        <a-input @input="changeDays" v-model="formData.executeDays" placeholder="请输入计划工期"></a-input>
      </a-form-item>
      <a-form-item label="负责人" field="userId">
        <SelectSearch
          v-if="isDetailLoaded"
          :params="{ customerId:currentCustomerId}"
          :defaultSelectId="formData.userId"
          :defaultSelectList="currentDirectorList"
          @change-select="changeRoleSelect"
          placeholder="请输入负责人"
          :request-api="memberByRoleId"
          :config="{ keyword: 'userName', label: 'nickName', value: 'userId' }"
        ></SelectSearch>
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="dialog-footer">
        <a-button  @click="handleCancel">取消 </a-button>
        <a-button :disabled="isLoading" type="primary"  @click="handleConfirm" >确定并调整</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup>
import { computed, ref, getCurrentInstance } from "vue";
import { debounce } from "lodash";
import {adjustPlanDetail,changeTime,submitAdjustTime,memberByRoleId} from "@/apis/home";
import SelectSearch from "@/components/selectSearch/index.vue"
import { Message } from "@arco-design/web-vue";


const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  currentStageTaskId: {
    type: String,
    default: ""
  },
  currentCustomerId: {
    type: String,
    default: ""
  }
});
const currentStageTaskId = props.currentStageTaskId ?? "";

const showAdjustTime = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const emit = defineEmits(["update:modelValue", "adjustTimeSave"]);

//表单相关
const formData = ref({
  executeDays: "",
  userId: "",
  timeRange: []
});
const formRule = {
  timeRange: [{ required: true, message: "请选择计划时间范围", trigger: "change" }],
  executeDays: [
    { required: true, message: "请输入计划工期", trigger: "blur" },
    { validator: (value, callback) => validatePositiveInteger(value, callback), trigger: "blur" }
  ],
  userId: [{ required: true, message: "请选择负责人", trigger: "change" }]
};
const validatePositiveInteger = (value, callback) => {
  value = Number(value);
  if (!Number.isInteger(value) || value <= 0) {
    callback(new Error("请输入正整数"));
  } else {
    callback();
  }
};

//时间
const changeDate = async () => {
  const timeRange = formData.value.timeRange;
  if (timeRange) {
    const params = {
      stageTaskId: currentStageTaskId,
      plainStartDate: timeRange[0],
      plainEndDate: timeRange[1],
      executeDays: 0
    };
    const { data } = await changeTime(currentStageTaskId, params);
    console.log("data", data);
    formData.value.timeRange = [data.plainStartDate, data.plainEndDate];
    formData.value.executeDays = data.executeDays;
  }
};
const changeDays = debounce(async () => {
  const timeRange = formData.value.timeRange;
  if (timeRange.length) {
    const params = {
      stageTaskId: currentStageTaskId,
      executeDays: formData.value.executeDays
    };
    const { data } = await changeTime(currentStageTaskId, params);
    console.log("data", data);
    formData.value.timeRange = [data.plainStartDate, data.plainEndDate];
    formData.value.executeDays = data.executeDays;
  }
}, 800);

//负责人
const currentDirectorList = ref([]);
const changeRoleSelect = data => {
  const { deptId, deptName, nickName, userId } = data;
  formData.value.userId = userId;
  formData.value.userName = nickName;
  formData.value.deptId = deptId;
  formData.value.deptName = deptName;
};


//详情
const isDetailLoaded = ref(false)
const getDetail = async () => {
  isLoading.value = true
  const { data } = await adjustPlanDetail(currentStageTaskId);
  formData.value = data;
  formData.value.timeRange = [data.plainStartDate, data.plainEndDate];
  currentDirectorList.value = [{ userId: data.userId, nickName: data.userName }];
  isLoading.value = false
  isDetailLoaded.value = true
};

//按钮操作
const isLoading = ref(false);
const handleCancel = () => {
  showAdjustTime.value = false;
};

const handleConfirm = async () => {
  proxy.$refs.formRef.validate(async valid => {
    if (valid) return Message.error("请完善信息");
    formData.value.plainStartDate = formData.value.timeRange[0];
    formData.value.plainEndDate = formData.value.timeRange[1];
    await submitAdjustTime(formData.value);
    isLoading.value = true;
    Message.success("计划调整成功");
    showAdjustTime.value = false;
    emit("adjustTimeSave");
  });
};

getDetail()
</script>

<style scoped lang="scss">
.header {
  display: flex;
  justify-content: space-between;
}
.customer-info {
  color: #86909c;
  font-size: 14px;
  margin-bottom: 20px;
}
.plan-form {
  :deep(.el-input__wrapper),
  :deep(.el-textarea__inner) {
    box-shadow: none;
  }
}

  :deep(.arco-picker),:deep(.arco-select),:deep(.arco-input),:deep(.arco-input-wrapper){
    border: none;
    background: #F2F3F5 !important;
  }
  .dialog-footer{
    :deep(button){
      width: 92px;
      height: 32px;
      line-height: 32px;
      &:first-child{
        margin-right: 10px;
        background: #f2f3f5;
      }
    }
  }
</style>
